/**
 *  This file is part of AugeasWH.
 *
 *  AugeasWH. is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AugeasWH. is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AugeasWH.  If not, see <http://www.gnu.org/licenses/>.
 */

package cz.fit.vutbr.pis2012.augeaswh.control.administration.user;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.validator.*;
import javax.faces.context.FacesContext;

import javax.faces.validator.ValidatorException;

import cz.fit.vutbr.pis2012.augeaswh.managers.UserManager;

@FacesValidator("usernameValidator")
@ManagedBean
public class UsernameValidator implements Validator {
	
	@EJB
	private UserManager um;

	@Override
	public void validate(FacesContext fc, UIComponent comp1, Object value) throws ValidatorException {
		String userName = (String) value;
		
		// Firstly check whether length of username is more than 6 characters
		if (userName.length() < 6) {
			FacesMessage message = new FacesMessage();
			message.setDetail("Username must be at least 6 characters long");
			message.setSummary("Username must be at least 6 characters long");
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
		
		// Check if username is not already taken
		if (um != null && um.getUserByName(userName) != null) {
			FacesMessage message = new FacesMessage();
			message.setDetail("Username is already taken");
			message.setSummary("Username is already taken");
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}

	}

}
